Component({
    data: {
        selected: 0,
        centerSelected: false,
        color: "#7A7E83",
        selectedColor: "#3cc51f",
        centerIconPath: "/components/custom-tab-bar/images/center-icon.png",
        showPlaceholder: true,
        centerPagePath: "pages/main/main",
        list: [
            {
                pagePath: "pages/index/index",
                text: "发现"
            },
            {
                pagePath: "pages/mall/mall",
                text: "商城"
            },
            {
                pagePath: "pages/matrix/matrix",
                text: "阵列"
            },
            {
                pagePath: "pages/mine/mine",
                text: "我的"
            }
        ]
    },
    attached() {
        this.setCurrentPage();
    },
    pageLifetimes: {
        show() {
            this.setCurrentPage();
        }
    },
    methods: {
        setCurrentPage() {
            const pages = getCurrentPages();
            const currentPage = pages[pages.length - 1];
            const url = currentPage.route;
            const tabBarList = this.data.list;
            
            // 检查是否是中间按钮对应的页面
            if (url === this.data.centerPagePath) {
                this.setData({
                    selected: -1,
                    centerSelected: true
                });
                return;
            }
            
            // 检查是否是其他 tabbar 页面
            for (let i = 0; i < tabBarList.length; i++) {
                if (tabBarList[i].pagePath === url) {
                    this.setData({
                        selected: i,
                        centerSelected: false
                    });
                    break;
                }
            }
        },
        switchTab(e) {
            const data = e.currentTarget.dataset;
            const url = '/' + data.path;
            wx.switchTab({
                url: url,
                success: () => {
                    this.setData({
                        selected: data.index,
                        centerSelected: false
                    });
                }
            });
        },
        onImageError() {
            this.setData({
                showPlaceholder: true
            });
        },
        onCenterButtonTap() {
            wx.switchTab({
                url: '/pages/main/main',
                success: () => {
                    this.setData({
                        selected: -1,
                        centerSelected: true
                    });
                }
            });
        }
    }
});
